package com.demo.core.logCore;

import com.demo.config.LogInit;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;

import java.io.*;

/**
 * A wrapper class which takes a logger as constructor argument and offers a
 * PrintStream whose flush method writes the written content to the supplied
 * logger (debug level).
 * <p>
 * Usage:<br>
 * initializing in @BeforeClass of the unit test:
 * <p>
 * <pre>
 * ToLoggerPrintStream loggerPrintStream = new ToLoggerPrintStream(myLog);
 * RestAssured.config = RestAssured.config().logConfig(new LogConfig(loggerPrintStream.getPrintStream(), true));
 * </pre>
 * <p>
 * will redirect all log outputs of a ValidatableResponse to the supplied
 * logger:
 * <p>
 * <pre>
 * resp.then().log().all(true);
 * </pre>
 *
 * @author Graham
 */
public class ToLoggerPrintStream {
    /**
     * Logger for this class
     */
    private static Logger logger = LogInit.getInstance();
    private PrintStream myPrintStream;

    /**
     * @return printStream
     */
    public PrintStream getPrintStream() {
        if (myPrintStream == null) {
            OutputStream output = new OutputStream() {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                @Override
                public void write(int b) throws IOException {

                    baos.write(b);

                }

                /**
                 * @see OutputStream#flush()
                 */
                @Override
                public void flush() {

                    String log = this.baos.toString().trim();

                    if (!StringUtils.isBlank(log)) {
                        logger.info(log);
                        baos = new ByteArrayOutputStream();
                    }
                }
            };
            // true: autoflush
            // must be set!
            myPrintStream = new PrintStream(output, true);

        }
        return myPrintStream;
    }
}
